package com.huaxinkai.mobile.util.wechatUtil;

import java.util.Arrays;

import com.huaxinkai.mobile.entity.JsAPITicket;
import com.huaxinkai.mobile.util.common.HttpUtil;
import com.huaxinkai.mobile.util.common.Sha1Util;
import com.huaxinkai.mobile.util.common.UUIDUtils;
import com.huaxinkai.mobile.util.wechatUtil.bean.wxconfig.WxConfig;

import net.sf.json.JSONObject;
/**
 * js api ticket 工具类
 * @author liuzh
 * @date 2017年1月5日下午11:30:57
 */
public class WechatJSTicketUtil {
	
	/**
	 * 通过 token 获取js ticket
	 * @param token
	 * @return
	 */
	public static JsAPITicket getJSTicket(String token){
		JsAPITicket ticket = null;
		String url = WechatConfig.WECHAT_JS_API_TICKET.replace("ACCESS_TOKEN", token);
		JSONObject result = HttpUtil.doGetJSON(url);
		if(result != null && !"".equals(result)){
			ticket = new JsAPITicket();
			ticket.setTicket(result.getString("ticket"));
		}
		return ticket;
	}
	/**
	 * 本地    通过 token 获取js ticket
	 * @param token
	 * @return
	 */
	public static void localUpdateJSTicket(){
		JsAPITicket ticket = null;
		String url = WechatConfig.UPDATE_JS_API_TICKET;
		JSONObject result = HttpUtil.doGetJSON(url);
		if(result != null && !"".equals(result)){
			ticket = new JsAPITicket();
			ticket.setTicket(result.getString("ticket"));
		}
	}
	
	public static WxConfig getWXConfig(String weburl,String ticket){
		/**
		 * jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg
		 * &noncestr=Wm3WZYTPz0wzccnW
		 * &timestamp=1414587457
		 * &url=http://mp.weixin.qq.com?params=value
		 */
		
		WxConfig wxConfig = new WxConfig();
		
		String noncestr = UUIDUtils.randomUUID();
		
		String jsapi_ticket = ticket;
		
		String timestamp = wxConfig.getTimestamp()+"";
		
		String url = weburl;
		
		//存入数组排序
		String arr[] = {
				"noncestr="+noncestr,
				"jsapi_ticket="+jsapi_ticket,
				"timestamp="+timestamp,
				"url="+url
				};
		
		Arrays.sort(arr);
		
		//拼接
		StringBuffer content = new StringBuffer();
		
		for (String str : arr) {
			content.append(str + "&");
		}
		String sign = content.toString();
		sign = sign.substring(0, sign.length() - 1);
		
		wxConfig.setNonceStr(noncestr);
		System.out.println( sign );
		wxConfig.setSignature(Sha1Util.getSha1( sign ));
		
		return wxConfig;
	}
	
	public static void main(String[] args){
		String hh = "jsapi_ticket=kgt8ON7yVITDhtdwci0qeQbgD7GZ5n0o6cpt-U1vMNZsRXEY5PedX8ZFTiORv3oBWTEgLc6NYvTGv1c-lNtiOg&noncestr=ed3c28aadfc74c2da54dfaa1956c66f6&timestamp=1483646598&url=http%3A%2F%2Fhuaxinkai.imwork.net%2Fhello%2FgoUpload";
		String a = Sha1Util.getSha1(hh);
		System.out.println(a);
	}
}
